﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using DigitalSolutionControls;
using System.Threading;
using System.Data;
using DigitalSolutionLibrary.SqlDatabase;
using System.Reflection;
using System.Linq;

namespace DigitalSolutionManagement
{
    public class BaseFormList:Form
    {
        private Thread th;
        private delegate void UpdateUI(DataSet ds, int totalPage);
        private ListPanel listPanel;
        private ModifiedDataGridView modifiedDataGridView;
        private Processing processing;
        private Paging paging;

        protected string LoadDataStore { get; set; }
        protected string DeleteItemStore { get; set; }
        protected BaseFormEdit EditForm { get; set; }
        protected frmViewReport.ReportType RptTye { get; set; }

        public BaseFormList()
        {
            this.MdiParent = Program.main;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BackColor = Color.WhiteSmoke;
            this.ControlBox = false;
            this.ShowIcon = false;
            BaseFormEdit.RefreshEvent += new EventHandler(BaseFormEdit_RefreshEvent);
        }

        void BaseFormEdit_RefreshEvent(object sender, EventArgs e)
        {
            if (sender.ToString() == this.Name)
            {
                paging.CurrentPage = 1;
                processing.ShowProcessing();
                th = new Thread(() => FillData(1));
                th.Start();
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!DesignMode)
            {
                this.FormBorderStyle = FormBorderStyle.None;
                this.Dock = DockStyle.Fill;

                //init control
                modifiedDataGridView = (ModifiedDataGridView)Controls["modifiedDataGridView1"];
                processing = (Processing)Controls["processing1"];
                paging = (Paging)Controls["paging1"];
                listPanel = (ListPanel)Controls["listPanel1"];

                //event
                listPanel.AddClick += new EventHandler(listPanel_AddClick);
                listPanel.EditClick += new EventHandler(listPanel_EditClick);
                listPanel.ViewClick += new EventHandler(listPanel_ViewClick);
                listPanel.DeleteClick += new EventHandler(listPanel_DeleteClick);
                paging.PageChanged += new EventHandler(paging_PageChanged);
                FormClosing += new FormClosingEventHandler(BaseFormList_FormClosing);

                //setup list panel
                listPanel.VisibleAdd = Program.main.HavePermission(listPanel.TextAdd);
                listPanel.VisibleDelete = Program.main.HavePermission(listPanel.TextDelete);
                listPanel.VisibleEdit = Program.main.HavePermission(listPanel.TextEdit);
                listPanel.VisibleView = Program.main.HavePermission(listPanel.TextView);

                //start load data
                processing.ShowProcessing();
                th = new Thread(() => FillData(1));
                th.Start();
            }
        }

        void BaseFormList_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th != null && th.IsAlive)
                th.Abort();
        }

        void paging_PageChanged(object sender, EventArgs e)
        {
            processing.ShowProcessing();
            th = new Thread(() => FillData((int)sender));
            th.Start();
        }

        void listPanel_DeleteClick(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show("Bạn có chắc muốn xóa không?","DSCo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (rs == System.Windows.Forms.DialogResult.Yes)
            {
                processing.ShowProcessing();
                th = new Thread(() => DelItem((int)modifiedDataGridView.SelectedRows[0].Cells["ColId"].Value));
                th.Start();
            }
        }

        void listPanel_ViewClick(object sender, EventArgs e)
        {
            frmViewReport frmViewRpt = new frmViewReport(RptTye);
            frmViewRpt.ItemId = (int)modifiedDataGridView.SelectedRows[0].Cells["ColId"].Value;
            frmViewRpt.Show();
        }

        void listPanel_EditClick(object sender, EventArgs e)
        {
            BaseFormEdit frm = EditForm.GetNewInstance(BaseFormEdit.OpenMode.EDIT);
            frm.ItemId = (int)modifiedDataGridView.SelectedRows[0].Cells["ColId"].Value;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                processing.ShowProcessing();
                th = new Thread(() => FillData(paging.CurrentPage));
                th.Start();
            }
        }

        void listPanel_AddClick(object sender, EventArgs e)
        {
            if (EditForm.GetNewInstance(BaseFormEdit.OpenMode.NEW).ShowDialog() == DialogResult.OK)
            {
                paging.CurrentPage = 1;
                processing.ShowProcessing();
                th = new Thread(() => FillData(1));
                th.Start();
            }
        }

        #region update control UI
        private void UpdateControl(DataSet ds, int totalPage)
        {
            modifiedDataGridView.DataSource = ds.Tables[0];
            paging.TotalPage = totalPage;
            listPanel.EnableDelete = listPanel.EnableEdit = listPanel.EnableView = modifiedDataGridView.SelectedRows.Count > 0;
            processing.HideProcessing();
        }
        #endregion

        #region Fill data for gridview
        private void FillData(int page)
        {
            Parameter par = new Parameter("CurPage", page, SqlDbType.Int);
            ParameterStock stock = new ParameterStock();
            stock.AddParamter(par);

            par = new Parameter("RowPerPage", Program.RowPerPage, SqlDbType.Int);
            stock.AddParamter(par);

            par = new Parameter("TotalPage", null, SqlDbType.Int, ParameterDirection.Output);
            stock.AddParamter(par);

            object obj = Program.dbWrapper.ExecuteStore(LoadDataStore, stock, DatabaseWrapper.ReturnType.DATASET);
            if (obj != null)
            {
                DataSet ds = (DataSet)obj;
                int totalPage = (int)stock.GetAtPosition(2).ValueOut;
                UpdateUI uui = new UpdateUI(UpdateControl);
                Invoke(uui, new object[] { ds, totalPage });
            }
            else
            {
                processing.HideProcessing();
                MessageBox.Show("Không thể kết nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region delete item
        private void DelItem(int id)
        {
            Parameter par = new Parameter("ItemId", id, SqlDbType.Int);
            ParameterStock stock = new ParameterStock();
            stock.AddParamter(par);

            par = new Parameter("RowPerPage", Program.RowPerPage, SqlDbType.Int);
            stock.AddParamter(par);

            object obj = Program.dbWrapper.ExecuteStore(DeleteItemStore, stock, DatabaseWrapper.ReturnType.FIRST_CELL);
            if (obj != null)
            {
                int tp = (int)obj;
                if (paging.CurrentPage > tp)
                {
                    paging.CurrentPage = tp;
                    paging.TotalPage = tp;
                    FillData(tp);
                }
                else
                {
                    FillData(paging.CurrentPage);
                }
            }
            else
            {
                processing.HideProcessing();
                MessageBox.Show("Không thể kết nối đến CSDL, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
    }
}
